package com.ruoyi.paiban.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.ruoyi.paiban.domain.PaibanResult2QianDuan;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.paiban.domain.Paiban;
import com.ruoyi.paiban.service.IPaibanService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 员工排班Controller
 * 
 * @author beilian
 * @date 2023-03-31
 */
@Controller
@RequestMapping("/paiban/paibanTest")
public class PaibanController extends BaseController
{
    private String prefix = "paiban/paibanTest";

    @Autowired
    private IPaibanService paibanService;

    @RequiresPermissions("paiban:paibanTest:view")
    @GetMapping()
    public String paibanTest()
    {
        return prefix + "/paibanTest";
    }

    /**
     * 查询员工排班列表
     */
    @RequiresPermissions("paiban:paibanTest:list")
    @PostMapping("/list")
    @ResponseBody
    public List<List<PaibanResult2QianDuan>> list(String year,String month, HttpServletRequest request) throws ParseException {
        List<List<PaibanResult2QianDuan>> list2qianduan = new ArrayList<>();
        String date = year+"-"+month;
        List<PaibanResult2QianDuan> list1 = paibanService.selectPaiban2Date(date,"1");
        List<PaibanResult2QianDuan> list2 = paibanService.selectPaiban2Date(date,"2");
        List<PaibanResult2QianDuan> list3 = paibanService.selectPaiban2Date(date,"3");
        List<PaibanResult2QianDuan> list4 = paibanService.selectPaiban2Date(date,"4");
        List<PaibanResult2QianDuan> list5 = paibanService.selectPaiban2Date(date,"5");
        list2qianduan.add(list1);
        list2qianduan.add(list2);
        list2qianduan.add(list3);
        list2qianduan.add(list4);
        list2qianduan.add(list5);

        return list2qianduan;

    }
//    public List<Paiban> list(Paiban paiban1, HttpServletRequest request)
//    {
//        paiban1 = new Paiban();
//        List<Paiban> test = paibanService.selectPaibanList(paiban1);
//
//        return test;
//
//    }

    @PostMapping("/check2today")
    @ResponseBody
    public AjaxResult datalist(String year,String month,String day, HttpServletRequest request)
    {
        if (month.length() == 1) {
            month = "0"+month;
        }
        if (day.length() == 1) {
            day = "0"+day;
        }
        String date = year+"-"+month+"-"+day;
        String name = request.getSession().getAttribute("name4user").toString();
        Paiban paiban = paibanService.selectPaibanBydate(date);
        if (paiban == null) {
            return toAjax("当前日期不需要签到");
        }
        if (!paiban.getYuangongName().equals(name)) {
            return toAjax("当前登录账户与当日值班人员不匹配");
        }
        if (new SimpleDateFormat("yyyy-MM-dd").format(paiban.getDate()).equals(date)) {
            paiban.setQiandaoStatus("已签到");
        }else {
            paiban.setQiandaoStatus("未签到");
        }
        int a = paibanService.updatePaiban(paiban);
        if (a<0) {
            return toAjax("签到失败");
        }
        return toAjax("签到成功");
    }


    /**
     * 按日期查询员工排班列表
     */



    /**
     * 导出员工排班列表
     */
    @RequiresPermissions("paiban:paibanTest:export")
    @Log(title = "员工排班", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Paiban paiban)
    {
        List<Paiban> list = paibanService.selectPaibanList(paiban);
        ExcelUtil<Paiban> util = new ExcelUtil<Paiban>(Paiban.class);
        return util.exportExcel(list, "员工排班数据");
    }

    /**
     * 新增员工排班
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存员工排班
     */
    @RequiresPermissions("paiban:paibanTest:add")
    @Log(title = "员工排班", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Paiban paiban)
    {
        return toAjax(paibanService.insertPaiban(paiban));
    }

    /**
     * 修改员工排班
     */
    @RequiresPermissions("paiban:paibanTest:edit")
    @GetMapping("/edit/{year}/{month}/{day}")
    public String edit(@PathVariable("year") String year,@PathVariable("month") String month,@PathVariable("day") String day, ModelMap mmap,
                       HttpServletRequest request)
    {
        String date = "";
        Paiban paiban = paibanService.selectPaibanBydate(date);
        mmap.put("paiban", paiban);
        request.getSession().setAttribute("year",year);
        request.getSession().setAttribute("month",month);
        request.getSession().setAttribute("day",day);

        return prefix + "/edit";
    }

    /**
     * 修改保存员工排班
     */
    @RequiresPermissions("paiban:paibanTest:edit")
    @Log(title = "员工排班", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(Paiban paiban)
    {
        return toAjax(1);
    }


    @PostMapping("/IDreturn/{year}/{month}/{day}")
    @ResponseBody
    public String IDreturn(@PathVariable("year") String year,@PathVariable("month") String month,@PathVariable("day") String day)
    {
        String date = "2023-4-1";
        Paiban paiban = paibanService.selectPaibanBydate(date);
        return paiban.getId().toString();
    }
    //IDreturn
    /**
     * 删除员工排班
     */
    @RequiresPermissions("paiban:paibanTest:remove")
    @Log(title = "员工排班", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String date)
    {
        return toAjax(paibanService.deletePaibanByIds(date));
    }


    @GetMapping("/qiandao")
    public String qiandao(HttpServletRequest request){
        return "/paiban/paibanTest/qiandao";
    }

//    SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
//        Date date = new Date(System.currentTimeMillis());
//        tdate = formatter.format(date);
//        uname  = request.getSession().getAttribute("name4user");
@PostMapping("/qiandao")
public AjaxResult set(HttpServletRequest request) throws ParseException {

    SimpleDateFormat formatter= new SimpleDateFormat("yyyy-MM-dd");
        Date ttdate = new Date(System.currentTimeMillis());

        String tdate = formatter.format(new Date());
        String uname  = request.getSession().getAttribute("name4user").toString();
        Date date =  formatter.parse(tdate);

        Paiban p =  new Paiban();
        p.setDate(date);
        p.setYuangongName(uname);
        p.setQiandaoStatus("1");
        System.out.println("qqq1"+date);
        System.out.println("qqq2"+uname);

    return toAjax(paibanService.updataqiandao(p));
    }


    @GetMapping("/excelImport")
    public String excelImport()
    {
        return prefix + "/excelImport";
    }

    @PostMapping("/excel2Import")
    public AjaxResult excel2Import(MultipartFile file, HttpServletResponse response,
                                   HttpServletRequest request)
    {
        //将规定格式的xls文件转换成对应数据库字段
        InputStream inputStream; // 获取文件的输入流
        String dealResult = null;
        try {
            inputStream = file.getInputStream();
            
        int length = file.getOriginalFilename().split("\\.").length; // 获取文件名数组的长度
        String suffix = file.getOriginalFilename().split("\\.")[length - 1]; // 取得文件后缀名
        if ("xls".equals(suffix)) {
            dealResult = hssfDeal(inputStream, response, request); // 如果后缀为.xls则用HSSFWorkbook
        } else if ("xlsx".equals(suffix)) {
            dealResult = xssfDeal(file, response, request); // 后缀为.xlsx则用XSSFWorkbook
        }
        } catch (IOException | ParseException e) {
    e.printStackTrace();
}
        return toAjax(dealResult);
    }

    private String xssfDeal(MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws IOException, ParseException {
        List<String> dateList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        String dealResult = null; // 返回的处理结果
        // 创建workbook对象，读取整个文档
        //创建工作簿
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(file.getInputStream());
        System.out.println("xssfWorkbook对象：" + xssfWorkbook);
        //读取第一个工作表
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
        System.out.println("sheet对象：" + sheet);
        //获取最后一行的num，即总行数。此处从0开始计数
        int maxRow = sheet.getLastRowNum();
        System.out.println("总行数为：" + maxRow);
        for (int row = 0; row <= maxRow; row++) {
            //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
            if (sheet.getRow(row) == null) {
                continue;
            }
            int maxRol = sheet.getRow(row).getLastCellNum();
            System.out.println("--------第" + row + "行的数据如下--------");
            for (int rol = 0; rol < maxRol; rol++){
                if (sheet.getRow(row).getCell(rol) == null) {
                    continue;
                }
                String str = String.valueOf(sheet.getRow(row).getCell(rol));
                if (str.contains(".") || str.contains("月")) {
                    dateList.add(str);
                }else {
                    nameList.add(str);
                }
                System.out.print(str + " ");
            }
        }
        dealResult = inserts(dateList,nameList,dealResult);
        return dealResult;
    }

    private String hssfDeal(InputStream inputStream, HttpServletResponse response, HttpServletRequest request) throws IOException, ParseException {
        List<String> dateList = new ArrayList<>();
        List<String> nameList = new ArrayList<>();
        String dealResult = null; // 返回的处理结果
        // 创建workbook对象，读取整个文档
        POIFSFileSystem poifsFileSystem = new POIFSFileSystem(inputStream);
        HSSFWorkbook wb = new HSSFWorkbook(poifsFileSystem);
        // 读取页脚sheet
        HSSFSheet sheetAt = wb.getSheetAt(0);
        
        for (int row = 0; row <= sheetAt.getLastRowNum(); row++) {
            //获取最后单元格num，即总单元格数 ***注意：此处从1开始计数***
            if (sheetAt.getRow(row) == null) {
                continue;
            }
            int maxRol = sheetAt.getRow(row).getLastCellNum();
            System.out.println("--------第" + row + "行的数据如下--------");
            for (int rol = 0; rol < maxRol; rol++){
                if (sheetAt.getRow(row).getCell(rol) == null) {
                    continue;
                }
                String str = String.valueOf(sheetAt.getRow(row).getCell(rol));
                if (str.contains(".") || str.contains("月")) {
                    dateList.add(str);
                }else {
                    nameList.add(str);
                }
                System.out.print(str + " ");
            }
        }
        dealResult = inserts(dateList,nameList,dealResult);
        return dealResult;
    }
    
    private String inserts(List<String> dateList, List<String> nameList,String dealResult) throws ParseException {
        int dli = dateList.size();
        int nli = nameList.size();
        List<Paiban> list = new ArrayList<>();
        if (dli > nli) {
            for (int i = 0; i < nli; i++) {
                String dlStr = dateList.get(i);
                String nlStr = nameList.get(i);
                Paiban paiban = new Paiban();
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dlStr);
                paiban.setDate(date);
                paiban.setYuangongName(nlStr);
                paiban.setQiandaoStatus("未签到");
                list.add(paiban);
            }
        }else {
            for (int i = 0; i < dli; i++) {
                String dlStr = dateList.get(i);
                String nlStr = nameList.get(i);
                Paiban paiban = new Paiban();
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse(dlStr);
                paiban.setDate(date);
                paiban.setYuangongName(nlStr);
                paiban.setQiandaoStatus("未签到");
                list.add(paiban);
            }
        }
        boolean bo = false;
        for (Paiban p:list) {
            int a = paibanService.insertPaiban(p);
            if (a < 0) {
                return "Excel导入失败";
            }
            bo = true;
        }
        if (bo) {
            return "导入成功";
        }
        return "Excel导入失败";
    }
}
